package com.hmall.cart.listener;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hmall.cart.service.ICartService;
import com.hmall.common.utils.UserContext;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Component
@RequiredArgsConstructor
@Slf4j
@RabbitListener(queues = "cart.clear.queue")
public class CartClearListener {
    private final ICartService cartService;

    @Autowired
    private ObjectMapper objectMapper; // 注入 ObjectMapper

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "cart.clear.queue"),
            exchange = @Exchange(name = "trade.topic", type = "topic"),
            key = "order.create"),
            containerFactory = "rabbitListenerContainerFactory")
    public void paySuccessClear(byte[] message) {
        try {
            Map<String, Object> payload = objectMapper.readValue(message, new TypeReference<Map<String, Object>>() {});
            Long userId = (Long) payload.get("userId");
            List<Long> itemIds = (List<Long>) payload.get("itemIds");

            log.info("收到订单创建消息，准备清理购物车，用户ID：{}, 商品ID列表：{}", userId, itemIds);

            if (userId == null || itemIds == null || itemIds.isEmpty()) {
                log.warn("消息内容不完整，跳过处理");
                return;
            }

            cartService.deleteCartItemByIds(userId, itemIds);
        } catch (Exception e) {
            log.error("处理 RabbitMQ 消息失败，消息内容: {}", new String(message), e);
        }
    }

}


